package tsif.tcluster.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageEncoder;

import java.io.DataOutput;
import java.io.IOException;
import java.util.List;

import tsif.tcluster.netty.impl.NettyCodecUtils;
import tsif.tcluster.netty.impl.NettyCodecUtils.IEncode;

/**
 * 协议加密器<br>
 * 
 */
public class TClusterNettyEncoder extends MessageToMessageEncoder<TClusterNettyMessage> {
	/** 编码器 **/
	protected static IEncode<TClusterNettyMessage> encode = new IEncode<TClusterNettyMessage>() {
		@Override
		public void write(TClusterNettyMessage obj, DataOutput outBuf) throws IOException {
			// write msg
			outBuf.writeLong(obj.getSourceServiceId());
			outBuf.writeLong(obj.getTargetServiceId());
			outBuf.writeShort(obj.getCode());

			// write data
			byte[] data = obj.getData();
			int datalen = (data != null) ? data.length : 0;
			outBuf.writeShort(datalen);
			outBuf.write(data);
		}
	};

	@Override
	protected void encode(ChannelHandlerContext ctx, TClusterNettyMessage obj, List<Object> out) throws Exception {

		// 统计数据长度
		int length = obj.calcLength() + 1 + NettyCodecUtils.MSG_HEAD_SIZE; // 算上消息头
		byte mode = 0;
		if (length > 1000) {
			mode = (byte) (mode | NettyCodecUtils.MODE_GZIP);
		}
		// 申请数据流
		ByteBuf buffer = ctx.alloc().buffer(length);
		// 编码输出
		NettyCodecUtils.encode(buffer, obj, mode, encode);
		// 输出内容
		out.add(buffer);
	}

}
